from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from utils.log_utils import logger


class BasePage:
    # 注意：单下换线是私有变量
    _base_url = ""

    def __init__(self, base_driver=None):
        if base_driver:
            logger.debug(f"复用已经存在的webdriver")
            self.driver = base_driver
        else:
            logger.debug(f"新创建一个webdriver")
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
            self.driver.implicitly_wait(3)

        logger.debug(f"当前url地址为{self.driver.current_url}")
        if not self.driver.current_url.startswith("http"):
            self.driver.get(self._base_url)
            logger.debug(f"新的url地址为{self._base_url}")

    def do_find(self, by, locator=None):
        if locator:
            return self.driver.find_element(by, locator)
        else:
            return self.driver.find_element(*by)

    def do_finds(self, by, locator=None):
        if locator:
            return self.driver.find_elements(by, locator)
        else:
            return self.driver.find_elements(*by)

    def do_send_keys(self, value, by, locator=None):
        ele = self.do_find(by, locator)
        ele.clear()
        ele.send_keys(value)

    def do_quit(self):
        self.driver.quit()

    def wait_visible(self, locator: tuple):
        return WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located(locator))
